//
//  GRRegisterViewController.m
//  YC_GRice
//
//  Created by LiuFeng on 2018/7/12.
//  Copyright © 2018年 YeCai. All rights reserved.
//

#import "GRRegisterViewController.h"
#import "LFTextField.h"
#import "UIButton+Common.h"

@interface GRRegisterViewController () <LFTextFieldDelegate>
{
    NSString *authcodeType;  // 验证码类型
}
/**
 Layout
 */
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topLayout;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *heightLayout;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *pwdHeightLayout;

@property (weak, nonatomic) IBOutlet UILabel *titleMode;
@property (weak, nonatomic) IBOutlet UILabel *warmPrompt;
@property (weak, nonatomic) IBOutlet UILabel *registerProcotol;
@property (weak, nonatomic) IBOutlet UIView *authcodeView;
@property (weak, nonatomic) IBOutlet UIView *passwordView;

@property (weak, nonatomic) IBOutlet LFTextField *mobileTF;
@property (weak, nonatomic) IBOutlet LFTextField *authcodeTF;
@property (weak, nonatomic) IBOutlet LFTextField *passwordTF;

@property (weak, nonatomic) IBOutlet UIButton *sureBtn;
@property (weak, nonatomic) IBOutlet UIButton *forgetPwdBtn;

@end

@implementation GRRegisterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.    
    [self adjustLayout];
}

- (void)adjustLayout {
    if (IS_IPHONEX) {
        _topLayout.constant = 103;
    }

    _mobileTF.limitNum     = 11;
    _authcodeTF.limitNum = 6;
    _passwordTF.limitNum = 16;
    
    _mobileTF.secureTextEntry = NO;

    switch (self.registerMode) {
        case GRRegisterModeAssociatedMobile:{
            authcodeType              = @"bind";
            _titleMode.text           = @"关联手机号码";
            _warmPrompt.text          = @"为了您的账户安全，请关联手机号码";
            _passwordView.hidden      = YES;
            _passwordTF.hidden = YES;
            _pwdHeightLayout.constant = 0;
        }
            break;
            
        case GRRegisterModeNewAccount:{
            authcodeType              = @"register";
            _titleMode.text           = @"注册账号";
            _registerProcotol.hidden  = NO;
        }
            break;
            
        case GRRegisterModeSetLoginPassword:{
            authcodeType             = @"password";
            _titleMode.text           = @"设置登录密码";
        }
            break;
            
        case GRRegisterModeModifyLoginPassword:{
            _titleMode.text           = @"修改密码";
            _mobileTF.limitNum        = 16;
            _mobileTF.placeholder     = @"输入旧密码";
            _mobileTF.secureTextEntry = YES;
            _mobileTF.keyboardType    = UIKeyboardTypeDefault;
            _warmPrompt.text          = @"修改成功后，请妥善保存您的密码";
            _forgetPwdBtn.hidden      = NO;
            _authcodeView.hidden      = YES;
            _heightLayout.constant    = 0;
        }
            break;
            
        case GRRegisterModeForgetLoginPassword:{
            authcodeType              = @"password";
            _titleMode.text           = @"忘记密码";
            _warmPrompt.text          = @"请妥善保存您的密码";
            _heightLayout.constant    = 55;
            _authcodeView.hidden      = NO;
            _forgetPwdBtn.hidden      = YES;
            _mobileTF.placeholder      = @"输入手机号码";
            _mobileTF.keyboardType    = UIKeyboardTypeNumberPad;
        }
            break;
            
        case GRRegisterModeSetTradePassword:{
            authcodeType                    = @"safePassword";
            _titleMode.text                  = @"交易密码";
            _warmPrompt.text              = @"用于龟米互赠时验证使用";
            _passwordTF.limitNum         = 6;
            _passwordTF.placeholder     = @"请设置6位纯数字密码";
            _passwordTF.keyboardType  = UIKeyboardTypeNumberPad;
        }
            break;
            
        case GRRegisterModeModifyTradePassword:{
            _titleMode.text           = @"修改交易密码";
            _mobileTF.limitNum        = 6;
            _passwordTF.limitNum      = 6;
            _mobileTF.placeholder     = @"输入旧密码";
            _mobileTF.secureTextEntry = YES;
            _warmPrompt.text          = @"修改成功后，请妥善保存您的密码";
            _authcodeView.hidden      = YES;
            _forgetPwdBtn.hidden      = NO;
            _heightLayout.constant    = 0;
            _passwordTF.placeholder   = @"请设置6位纯数字密码";
            _passwordTF.keyboardType  = UIKeyboardTypeNumberPad;
        }
            break;
            
        default:{
            authcodeType              = @"safePassword";
            _titleMode.text           = @"忘记交易密码";
            _warmPrompt.text          = @"请妥善保存您的密码";
            _mobileTF.placeholder     = @"输入手机号码";
            _mobileTF.limitNum        = 11;
            _passwordTF.limitNum      = 6;
            _heightLayout.constant    = 55;
            _authcodeView.hidden      = NO;
            _forgetPwdBtn.hidden      = YES;
            _passwordTF.placeholder   = @"请设置6位纯数字密码";
            _passwordTF.keyboardType  = UIKeyboardTypeNumberPad;
        }
            break;
    }

}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)getVerificationCode:(id)sender {
    NSDictionary *dictionary = @{@"paramer": @{@"mobile":self.mobileTF.text,
                                               @"type"  :authcodeType,
                                               @"app"   :@"gm"
                                               },
                                 @"sender" : sender
                                 };
    [GRLoginAction getVerificationCode:dictionary];
}

- (IBAction)forgetPassword:(id)sender {
    switch (self.registerMode) {
        case GRRegisterModeModifyLoginPassword:
            self.registerMode = GRRegisterModeForgetLoginPassword;
            break;
            
        default:
            self.registerMode = GRRegisterModeForgetTradePassword;
            break;
    }
    [self adjustLayout];
}


- (IBAction)didFinishOperation:(UIButton *)sender {
    sender.enabled = NO;
WEAKSELF
    if (self.registerMode == GRRegisterModeAssociatedMobile) {
        NSDictionary *param = @{
                                @"avatar"  : self.UMResponse.iconurl,
                                @"code"    : self.authcodeTF.text,
                                @"mobile"  : self.mobileTF.text,
                                @"name"    : self.UMResponse.name,
                                @"openId"  : self.UMResponse.openid,
                                @"sex"     : [self.UMResponse.gender isEqualToString:@"f"] ? @"female" : @"male",
                                @"unionId" : self.UMResponse.unionId,
                                @"sourceWechat": @"app"
                                };
        [GRLoginAction associatedMobile:param completionHandler:^(BOOL success, id responseObject, GRError *error) {
            if (success) {
                [weakSelf LoginSuccess:responseObject];
                [weakSelf dismissALLViewController];
            }else {
                [[LFAlertBox defaultAlert] showAlertContent:[error errorMsg] sure:@"确定" completion:nil];
            }
            sender.enabled = YES;
        }];
        
    }else if (self.registerMode == GRRegisterModeModifyLoginPassword || self.registerMode == GRRegisterModeModifyTradePassword) {
        
        NSDictionary *paramer = @{@"oldPassword" : self.mobileTF.text,
                                  @"newPassword" : self.passwordTF.text,
                                  @"oldSafePassword" : self.mobileTF.text,
                                  @"newSafePassword" : self.passwordTF.text
                                  };
        
        [GRLoginAction modifyPasswordWithRegisterMode:self.registerMode paramers:paramer completionHandler:^(BOOL success, id responseObject, GRError *error) {
            if (success) {
                [[LFAlertBox backgroundAlert] showAlertContent:@"修改成功" sure:@"确定" completion:^(NSInteger index) {
                    [self.navigationController popViewControllerAnimated:YES];
                }];
            }else {
                [[LFAlertBox defaultAlert] showAlertContent:[error errorMsg] sure:@"确定" completion:nil];
            }
            sender.enabled = YES;
        }];
        
    }else {
        
        NSDictionary *paramer = @{@"mobile"   : self.mobileTF.text,
                                  @"code"     : self.authcodeTF.text,
                                  @"password" : self.passwordTF.text,
                                  @"safePassword": self.passwordTF.text,
                                  @"sourceWechat": @"app"
                                  };
        
        [GRLoginAction setPasswordWithRegisterMode:self.registerMode paaramers:paramer completionHandler:^(BOOL success, id responseObject, GRError *error) {
            if (success) {
                if (weakSelf.registerMode == GRRegisterModeNewAccount) {
                    // 注册新账户 注册成功即登录成功
                    [weakSelf LoginSuccess:responseObject[@"responseObject"]];
                }else if (weakSelf.registerMode == GRRegisterModeSetLoginPassword || weakSelf.registerMode == GRRegisterModeSetTradePassword) {
                    // 设置密码 刷新状态
                    if (self.finishBlock) {
                        self.finishBlock();
                    }
                }
                [[LFAlertBox backgroundAlert] showAlertContent:responseObject[@"tip"] sure:@"确定" completion:^(NSInteger index) {
                    if (self.isTop) {
                        [self dismissALLViewController];
                    }else {
                        [self.navigationController popViewControllerAnimated:YES];
                    }
                }];
            }else {
                [[LFAlertBox defaultAlert] showAlertContent:[error errorMsg] sure:@"确定" completion:nil];
            }
            sender.enabled = YES;
        }];
    }
}


/**
 登录成功（微信登录或注册时，自动登录）

 @param responseObject <#responseObject description#>
 */
- (void)LoginSuccess:(id)responseObject {
    GRBasisKeyModel *model = [GRBasisKeyModel yy_modelWithDictionary:responseObject];
    if (model) {
        [[GRUserBasisInfo shareBasis] saveBasisKey:model];
        [[GRUserBasisInfo shareBasis] doLogin];
    }
}

/**
 实时监听键盘输入以改变按钮
 */
-(void)textField:(UITextField *)textField textDidChange:(NSString *)text {
    if (!self.authcodeTF.hidden && !self.passwordTF.hidden) {
        NSInteger length = _passwordTF.limitNum == 6 ? 6 : 8;
        if (self.authcodeTF.text.length >= _authcodeTF.limitNum && self.passwordTF.text.length >= length ) {
        [self changeSureBtn:YES];
        }else{
        [self changeSureBtn: NO];
        }
    }else {
        if ([textField isEqual:self.authcodeTF]) {
            [self changeSureBtn:text.length >= 6 ? YES : NO];
        }else {
            NSInteger length = _passwordTF.limitNum == 6 ? 6 : 8;
            [self changeSureBtn:text.length >= length ? YES : NO];
        }
    }
}

- (void)changeSureBtn:(BOOL)status {
    self.sureBtn.enabled         = status;
    self.sureBtn.backgroundColor = status ? KGMTHEM_COLOR : KGMBACKGROUND_COLOR;
    [self.sureBtn setTitleColor:status ? KGMBLACK_COLOR : HEXCOLOR(0x999999) forState:UIControlStateNormal];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
